<template>
  <div class="login">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ isLogin ? '登录界面' : '注册界面' }}</span>
      </div>
      <div class="text item">
        <el-form :model="userForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="账号" prop="username">
            <el-input v-model="userForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="userForm.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item v-if="!isLogin" label="确认密码" prop="confirmPassword">
            <el-input type="password" v-model="userForm.confirmPassword" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="login('ruleForm')">{{ isLogin ? '登录' : '注册' }}</el-button>
            <el-button @click="toggleMode">{{ isLogin ? '注册' : '登录' }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { loginApi, registerApi } from '@/api/index'
import { mapState, mapMutations } from 'vuex'
import { Message } from 'element-ui'
export default {
  data () {
    return {
      isLogin: true, // 当前是登录模式还是注册模式
      userForm: {
        username: '',
        password: '',
        confirmPassword: '' // 用于注册时的确认密码
      },
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^\S{3,15}$/, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请再次输入密码'))
              } else if (value !== this.userForm.password) {
                callback(new Error('两次输入密码不一致!'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },

  methods: {
    ...mapState(['token']),
    ...mapMutations(['updateToken']),
    async login () {
      try {
        const valid = await this.$refs.ruleForm.validate()
        if (valid) {
          console.log('表单验证通过')
          if (this.isLogin) {
            // 处理登录逻辑
            const { data: res } = await loginApi(this.userForm)
            console.log(res.access)
            this.updateToken(res.access)
            this.$message.success('登录成功')
            if (res.access) {
              this.$router.push({ path: '/home' })
            }
          } else {
            // 处理注册逻辑
            const { data: res } = await registerApi(this.userForm)
            console.log(res)
            // this.$message.success('注册成功')
            console.log('注册成功')
            // 注册成功后可以切换到登录模式
            // this.toggleMode()
          }
        } else {
          console.log('表单验证未通过')
          return false
        }
      } catch (error) {
        if (error.response && error.response.status === 401) {
          Message.error('登录失败，请重试')
        }
      }
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    toggleMode () {
      this.isLogin = !this.isLogin
      this.resetForm('ruleForm')
    }
  }
}
</script>

<style lang="less" scoped>
  .login{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100vh; /* 使用 100vh 确保高度为视口高度 */
    background: url('../../assets/image/6.jpg') no-repeat center center;
    background-size: cover;
    .box-card{
      display: flex;
      flex-direction: column;
      justify-content: center;
      width: 600px;
      height: 350px;
      margin: 0 auto;
      margin-top: 0px;
      background-color: rgba(255, 255, 255, 0.8);
      .clearfix{
        text-align: center;
      }
    }
  }
</style>
